package ranab.server.ftp;

import java.util.Date;
import java.util.List; 
import java.util.Collection;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.text.SimpleDateFormat;
import java.lang.reflect.Method;

import ranab.util.StringUtils;
import ranab.server.IpRestrictor;
import ranab.server.ftp.usermanager.User;
import ranab.server.ftp.usermanager.UserManager;

/**
 * Handle ftp site command.
 *
 * @author <a href="mailto:rana_b@yahoo.com">Rana Bhattacharyya</a>
 */
public
class SiteCommandHandler {
    
    protected final static SimpleDateFormat DATE_FMT = new SimpleDateFormat("MM/dd HH:mm:ss");
    protected final static Class[] INPUT_SIG = new Class[] {String[].class, FtpRequest.class};
    
    private FtpConfig mConfig;
    private FtpUser mUser;
    
    
    /**
     * Constructor - set the configuration object
     */
    public SiteCommandHandler(FtpConfig cfg, FtpUser user) {
        mConfig = cfg;
        mUser = user;
    }
    
    
    /**
     * Handle site.
     */
    public String getResponse(FtpRequest request) {
        String argArray[] = parseArg(request.getArgument());
        
        String response = "";
        if (hasPermission(argArray)) {
            if ((argArray != null) && (argArray.length != 0)) {
                try {
                    String metName = "do" + argArray[0].toUpperCase();
                    Method actionMet = getClass().getDeclaredMethod(metName, INPUT_SIG);
                    response = (String)actionMet.invoke(this, new Object[] {argArray, request});
                }
                catch(Throwable th) {
                    mConfig.getLogger().warn(th);
                    response = mConfig.getStatus().getResponse(530, request, mUser, null);
                }
            }
            else {
                response = mConfig.getStatus().getResponse(200, request, mUser, null);
            }
        }
        else {
            response = mConfig.getStatus().getResponse(530, request, mUser, null);
        }
        
        return response;
    }
    
    
    /**
     * Parse all the tokens.
     */
    private String[] parseArg(String arg) {
        if (arg == null) {
            return null;
        }
        
        StringTokenizer st = new StringTokenizer(arg, " ");
        String[] args = new String[st.countTokens()]; 
        for(int i=0; i<args.length; i++) {
            args[i] = st.nextToken();
        }
        
        return args;
    }
    
    
    /**
     * Has permission
     */
    private boolean hasPermission(String args[]) {
        UserManager userManager = mConfig.getUserManager();
        String adminName = userManager.getAdminName();
        if ( args == null || mUser.getName().equals(adminName) ) {
            return true;
        }
        return ( (args.length > 0) && "HELP".equalsIgnoreCase(args[0]) );
    }
     
     
    ////////////////////////////////////////////////////////////////////////////   
    ////////////////////////  All site command handlers //////////////////////// 
    /**
     * Add banned IP
     */
     public String doADDIP(String[] args, FtpRequest cmd) {
         if (args.length != 2) {
             return mConfig.getStatus().getResponse(501, cmd, mUser, null);
         }
         
         String response = "";
         try {
             IpRestrictor ipRestrictor = mConfig.getIpRestrictor();
             ipRestrictor.add(args[1]);
             ipRestrictor.writeFile();
             response = mConfig.getStatus().getResponse(200, cmd, mUser, null);
         }
         catch(Exception ex) {
             mConfig.getLogger().warn(ex);
             response = mConfig.getStatus().getResponse(451, cmd, mUser, null);
         }
         return response;
     } 


    /**
     * Add user
     */
     public String doADDUSER(String[] args, FtpRequest cmd) {
         if (args.length != 2) {
             return mConfig.getStatus().getResponse(501, cmd, mUser, null);
         }
         
         String response = "";
         try {
             User user = new User();
             user.setName(args[1]);
             user.setPassword("");
             user.setEnabled(false);
             user.getVirtualDirectory().setWritePermission(false);
             user.setMaxUploadRate(0);
             user.setMaxDownloadRate(0);
             user.getVirtualDirectory().setRootDirectory(mConfig.getDefaultRoot());
             user.setMaxIdleTime(mConfig.getDefaultIdleTime());
             mConfig.getUserManager().save(user);
             response = mConfig.getStatus().getResponse(200, cmd, mUser, null);
         }
         catch(Exception ex) {
             mConfig.getLogger().warn(ex);
             response = mConfig.getStatus().getResponse(451, cmd, mUser, null);
         }
         return response;
     } 

     
     /**
      * Add banned IP
      */
     public String doDELIP(String[] args, FtpRequest cmd) {
          if (args.length != 2) {
              return mConfig.getStatus().getResponse(501, cmd, mUser, null);
          }
          
          String response = "";
          try {
              IpRestrictor ipRestrictor = mConfig.getIpRestrictor();
              if (ipRestrictor.remove(args[1])) {
                ipRestrictor.writeFile();
              }
              response = mConfig.getStatus().getResponse(200, cmd, mUser, null);
          }
          catch(Exception ex) {
              mConfig.getLogger().warn(ex);
              response = mConfig.getStatus().getResponse(451, cmd, mUser, null);
          }
          return response;
    } 
      
           
    /**
     * Delete user from repository.
     */
    public String doDELUSER(String[] args, FtpRequest cmd) {
        if (args.length != 2) {
            return mConfig.getStatus().getResponse(501, cmd, mUser, null);
        }
        
        String response = "";
        try {
            mConfig.getUserManager().delete(args[1]);
            response = mConfig.getStatus().getResponse(200, cmd, mUser, null);
        }
        catch(Exception ex) {
            mConfig.getLogger().warn(ex);
            response = mConfig.getStatus().getResponse(451, cmd, mUser, null);
        }
        return response;
    } 
      
    /**
     * Describe user.
     */
    public String doDESCUSER(String[] args, FtpRequest cmd) {
        if (args.length != 2) {
            return mConfig.getStatus().getResponse(501, cmd, mUser, null);
        }
        
        StringBuffer sb = new StringBuffer();
        sb.append('\n');
        User user = mConfig.getUserManager().getUserByName(args[1]);
        if (user != null) {
            sb.append("login : ").append(user.getName()).append('\n');
            sb.append("password : ").append("******").append('\n');
            sb.append("home : ").append(user.getVirtualDirectory().getRootDirectory()).append('\n');
            sb.append("writepermission : ").append(user.getVirtualDirectory().getWritePermission()).append('\n');
            sb.append("enable : ").append(user.getEnabled()).append('\n');
            sb.append("maxidletime : ").append(user.getMaxIdleTime()).append('\n');
            sb.append("maxuploadrate : ").append(user.getMaxUploadRate()).append('\n');
            sb.append("maxdownloadrate : ").append(user.getMaxDownloadRate()).append('\n');
        }
        sb.append('\n');
        return mConfig.getStatus().processNewLine(sb.toString(), 200);
    }  
            
    
    /**
     * Display site help.
     */
    public String doHELP(String[] args, FtpRequest cmd) {
        StringBuffer sb = new StringBuffer();
        sb.append('\n');
        sb.append("ADDIP <IP> : add banned IP entry").append('\n');
        sb.append("ADDUSER <userName> : add user").append('\n');
        sb.append("DELIP <IP> : delete banned IP entry").append('\n');
        sb.append("DELUSER <userName> : delete user").append('\n');
        sb.append("DESCUSER <userName> : describe user").append('\n');
        sb.append("HELP : display this message").append('\n');
        sb.append("KICK <userName> : close the connection").append('\n');
        sb.append("LISTIP : display all banned IPs").append('\n');
        sb.append("LISTUSER : display all user names").append('\n');
        sb.append("SETATTR <userName> <attrName> <attrValue> : set user attributes").append('\n');
        sb.append("WHO : display all connected users").append('\n');
        sb.append('\n');
        return mConfig.getStatus().processNewLine(sb.toString(), 200);
    } 
   
    /**
     * Disconnect ftp connections
     */
    public String doKICK(String[] args, FtpRequest cmd) {
        if (args.length != 2) {
            return mConfig.getStatus().getResponse(501, cmd, mUser, null);
        }
        String userName = args[1];
        List allUsers = mConfig.getConnectionService().getAllUsers();
        for(Iterator userIt=allUsers.iterator(); userIt.hasNext(); ) {
            FtpUser user = (FtpUser)userIt.next();
            if ( userName.equals(user.getName()) ) {
                mConfig.getConnectionService().closeConnection(user.getSessionId());
            }
        }
        return mConfig.getStatus().getResponse(200, cmd, mUser, null);
    }
   
   
    /**
     * List all banned IPs.
     */
    public String doLISTIP(String[] args, FtpRequest cmd) {
        StringBuffer sb = new StringBuffer();
        sb.append('\n');
        for(Iterator ipIt=mConfig.getIpRestrictor().iterator(); ipIt.hasNext(); ) {
            sb.append(ipIt.next()).append('\n');
        }
        sb.append('\n');
        return mConfig.getStatus().processNewLine(sb.toString(), 200);
    }
   
   
    /**
     * List all the users.
     */
    public String doLISTUSER(String[] args, FtpRequest cmd) {
        Collection userNames = mConfig.getUserManager().getAllUserNames();
        StringBuffer sb = new StringBuffer();
        sb.append('\n');
        for(Iterator userIt=userNames.iterator(); userIt.hasNext(); ) {
            sb.append(userIt.next()).append('\n');
        }
        sb.append('\n');
        return mConfig.getStatus().processNewLine(sb.toString(), 200);
    }
   
   
    /**
     * Delete user from repository.
     */
    public String doSETATTR(String[] args, FtpRequest cmd) {
        if (args.length != 4) {
            return mConfig.getStatus().getResponse(501, cmd, mUser, null);
        }
        
        boolean bSuccess = true;
        try {
            User user = mConfig.getUserManager().getUserByName(args[1]);
            if (user != null) {
            
                if ( "password".equals(args[2]) ) {
                    user.setPassword(args[3]);
                }
                else if ( "home".equals(args[2]) ) {
                    user.getVirtualDirectory().setRootDirectory(args[3]);
                }
                else if ( "writepermission".equals(args[2]) ) {
                    user.getVirtualDirectory().setWritePermission("true".equals(args[3]));
                }
                else if ( "enable".equals(args[2]) ) {
                    user.setEnabled("true".equals(args[3]));
                }
                else if ( "maxidletime".equals(args[2]) ) {
                    user.setMaxIdleTime(Integer.parseInt(args[3]));
                }
                else if ( "maxuploadrate".equals(args[2]) ) {
                    user.setMaxUploadRate(Integer.parseInt(args[3]));
                }
                else if ( "maxdownloadrate".equals(args[2]) ) {
                    user.setMaxDownloadRate(Integer.parseInt(args[3]));
                }
                else {
                    bSuccess = false;
                }
                
                if (bSuccess) {
                    mConfig.getUserManager().save(user);
                }
            }
            else {
                bSuccess = false;
            }
        }
        catch(Exception ex) {
            mConfig.getLogger().warn(ex);
            bSuccess = false;
        }
        
        String response = "";
        if (bSuccess) {
            response = mConfig.getStatus().getResponse(200, cmd, mUser, null);
        }
        else {
            response = mConfig.getStatus().getResponse(451, cmd, mUser, null);
        }
        
        return response;
    }
    
   
    /**
     * Display all connected users.
     */
    public String doWHO(String[] args, FtpRequest cmd) {
        StringBuffer sb = new StringBuffer();
        List allUsers = mConfig.getConnectionService().getAllUsers();
        
        sb.append('\n');
        for(Iterator userIt = allUsers.iterator(); userIt.hasNext(); ) {
            FtpUser user = (FtpUser)userIt.next();
            if (!user.hasLoggedIn()) {
                continue;
            }
            sb.append( StringUtils.pad(user.getName(), ' ', true, 16) );
            sb.append( StringUtils.pad(user.getClientAddress().getHostAddress(), ' ', true, 16) );
            sb.append( StringUtils.pad(DATE_FMT.format(new Date(user.getLoginTime())), ' ', true, 16) );
            sb.append( StringUtils.pad(DATE_FMT.format(new Date(user.getLastAccessTime())), ' ', true, 16) );
            sb.append('\n');
        }
        sb.append('\n');
        return mConfig.getStatus().processNewLine(sb.toString(), 200);
    }
      
} 

